﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;
using SubStationManagement.Server.Models;

namespace SubStationManagement.Server.Services
{
    public class MeasureSampleService
    {
        private readonly IMongoCollection<MeasureSample> _measureSamplesCollection;

        public MeasureSampleService(
            IOptions<SubStationDatabaseSettings> subStationDatabaseSettings)
        {
            var mongoClient = new MongoClient(
                subStationDatabaseSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                subStationDatabaseSettings.Value.DatabaseName);

            _measureSamplesCollection = mongoDatabase.GetCollection<MeasureSample>(
                subStationDatabaseSettings.Value.MeasureSamplesCollectionName);
        }

        public async Task<List<MeasureSample>> GetAsync() =>
            await _measureSamplesCollection.Find(_ => true).ToListAsync();

        public List<MeasureSample> GetAll() =>
            _measureSamplesCollection.Find(_ => true).ToList();

        public async Task<MeasureSample?> GetAsync(string id) =>
            await _measureSamplesCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public async Task CreateAsync(MeasureSample newMeasureSample) =>
            await _measureSamplesCollection.InsertOneAsync(newMeasureSample);

        public async Task UpdateAsync(string id, MeasureSample updatedMeasureSample) =>
            await _measureSamplesCollection.ReplaceOneAsync(x => x.Id == id, updatedMeasureSample);

        public async Task RemoveAsync(string id) =>
            await _measureSamplesCollection.DeleteOneAsync(x => x.Id == id);
    }
}
